<script lang="ts" setup>
import type { FileType } from 'ant-design-vue/es/upload/interface';

import type { AiTrainingDatasetMetaApi } from '#/api/ai/dataset/trainingDatasetMeta';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { Button, message, Upload } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  importTrainingDatasetSamples,
  importTrainingDatasetSamplesTemplate,
} from '#/api/ai/dataset/trainingDatasetSamples';
import { $t } from '#/locales';

import { useImportFormSchema } from '../data';

const emit = defineEmits(['success']);
const failureList = ref([]);
const gridColumns = ref([]);
const showError = ref(false);
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 100,
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: useImportFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = await formApi.getValues();
    try {
      data.datasetId = data.id;
      const params = {
        ...data,
      };
      // 移除file
      delete params.file;
      const reqData = {
        file: data.file,
        params,
      };

      const ret = await importTrainingDatasetSamples(reqData);
      if (ret.failure > 0) {
        // 存在失败提供失败数据下载

        gridApi.setGridOptions({
          columns: ret.tableHeader || [],
          data: ret.failureList || [],
        });
        showError.value = true;
      } else {
        showError.value = false;
        // 全部导入成功
        // 关闭并提示
        await modalApi.close();
        emit('success');
        message.success($t('ui.actionMessage.operationSuccess'));
      }
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    // 加载数据
    const data =
      modalApi.getData<AiTrainingDatasetMetaApi.TrainingDatasetMeta>();
    data.versionNum = undefined;
    await formApi.setValues(data);
  },
});

/** 上传前 */
function beforeUpload(file: FileType) {
  formApi.setFieldValue('file', file);
  return false;
}

/** 下载模版 */
async function handleDownload() {
  // 判断数据类型
  const form = await formApi.getValues();
  const dataFormat = form?.dataFormat;
  if (!dataFormat) {
    message.error('请选择数据格式');
    return;
  }
  const data = await importTrainingDatasetSamplesTemplate(dataFormat);
  downloadFileFromBlobPart({ fileName: '数据集导入模板.xls', source: data });
}
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    id: 'PromptVariables-grid',
    columns: gridColumns.value,
    height: 'auto',
    pagerConfig: {
      enabled: false,
    },
    data: failureList.value,
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: false,
      search: false,
      export: true,
    },
    exportConfig: {
      filename: '导入失败数据',
      type: 'xlsx',
    },
  },
  gridEvents: {},
});
</script>

<template>
  <Modal title="导入数据" class="w-2/3">
    <Form class="mx-4" v-if="!showError">
      <template #file>
        <div class="w-full">
          <Upload
            :max-count="1"
            accept=".xls,.xlsx"
            :before-upload="beforeUpload"
          >
            <Button type="primary"> 选择 Excel 文件 </Button>
          </Upload>
        </div>
      </template>
    </Form>
    <Grid v-else table-title="错误数据" />
    <template #prepend-footer>
      <div class="flex flex-auto items-center" v-if="!showError">
        <Button @click="handleDownload"> 下载导入模板 </Button>
      </div>
    </template>
  </Modal>
</template>
